#include <string.h>
#include "driver/gpio.h"
#include "dvc.h"
#include "timer_task.h"
#include "board_v1_1_map.h"

typedef enum dvc_handle_type
{
    DVC_HANDLE_CHG, /* 充电 */
    DVC_HANDLE_DSG, /* 放电 */
    DVC_HANDLE_AES, /* 均衡 */
    DVC_HANDLE_IO,  /* IO */
    DVC_HANDLE_MAX, /*  */
} dvc_handle_type_t;

static const timer_action_handle_item_t dvc_handles[] = {
    {
        .name = "chg",
        .desc = "on/off charge",
        .i18n = "充电状态",
        .desc_i18n = "打开(1)/关闭(0) 充电",
    },
    {
        .name = "dsg",
        .desc = "on/off discharge",
        .i18n = "放电状态",
        .desc_i18n = "打开(1)/关闭(0) 放电",
    },
    {
        .name = "aes",
        .desc = "on/off AES",
        .i18n = "主动均衡状态",
        .desc_i18n = "打开(1)/关闭(0) 主动均衡",
    },
    {
        .name = "io",
        .desc = "on/off IO",
        .i18n = "外部IO状态",
        .desc_i18n = "打开(1)/关闭(0) 外部IO",
    },
};

static const timer_action_param_item_t dvc_params[] = {
    {
        .name = "close",
        .i18n = "关闭",
        .value = 0,
        .handles = 0xFF,
    },
    {
        .name = "open",
        .i18n = "打开",
        .value = 1,
        .handles = 0xFF,
    },
};

extern dvc_t gloab_dvc;
static uint8_t dvc_timer_action_cb(uint8_t handle, uint8_t param)
{
    if (handle >= DVC_HANDLE_MAX || param > 1 || !gloab_dvc)
        return ACTION_RESULT_FAIL;
    switch (handle)
    {
    case DVC_HANDLE_CHG:
    {
        dvc_chg(gloab_dvc, param > 0, DVC_EVENT_FLAG_SYS);
        dvc_config_commit(gloab_dvc);
    }
    break;
    case DVC_HANDLE_DSG:
    {
        dvc_dsg(gloab_dvc, param > 0, DVC_EVENT_FLAG_SYS);
        dvc_config_commit(gloab_dvc);
    }
    break;
    case DVC_HANDLE_AES:
    {
        dvc_aes(gloab_dvc, param > 0, DVC_EVENT_FLAG_SYS);
        break;
    }
    case DVC_HANDLE_IO:
    {
        gpio_config_t io_conf = {
            .mode = GPIO_MODE_OUTPUT,
            .pull_down_en = 0,
            .pull_up_en = 0,
            .pin_bit_mask = (1ULL << EXT_IO)};
        gpio_config(&io_conf);
        gpio_set_level(EXT_IO, param > 0);
        break;
    }
    default:
        return ACTION_RESULT_FAIL;
    }
    return ACTION_RESULT_SUCCESS;
}

ADD_TIMER_ACTION(AFE, dvc_timer_action_cb, dvc_handles, dvc_params)
